package com.game.modular.gameCore.cultivate.service.impl;

import lombok.extern.slf4j.Slf4j;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.game.modular.gameCore.cultivate.mapper.CoreExperienceMapper;
import com.game.modular.gameCore.cultivate.domain.CoreExperience;
import com.game.modular.gameCore.cultivate.service.CoreExperienceService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.annotation.PostConstruct;


/**
 * 全局经验表(CoreExperience)表服务实现类
 *
 * @author cxy
 * @since 2024-08-05 16:14:02
 */
@Slf4j
@Service
public class CoreExperienceServiceImpl extends ServiceImpl<CoreExperienceMapper, CoreExperience> implements CoreExperienceService {
    Cache<String, Map<String,CoreExperience>> cache = Caffeine.newBuilder().build();
    
    @PostConstruct
    private void init() {
        CoreExperience initSelect = CoreExperience.builder().build();
        List<CoreExperience> list = this.list(new LambdaQueryWrapper<>(initSelect));
        log.info("开始缓存全局经验表数据,数据量为:{}",list.size());
        cache.put(
                "coreExperience",
                list.stream().collect(Collectors.toMap(item-> item.getLevel()+"-"+item.getType(), CoreExperience -> CoreExperience))
        );
        log.info("全局经验表数据缓存完成");
    }

    public List<CoreExperience> listCache() {
        Map<String,CoreExperience> values = cache.getIfPresent("coreExperience");
        if (Objects.isNull(values)) {
            throw new RuntimeException("全局经验表数据为空");
        }
        return new ArrayList<>(values.values());
    }     
    
    public Map<String,CoreExperience> mapCache() {
        Map<String,CoreExperience> values = cache.getIfPresent("coreExperience");
        if (Objects.isNull(values)) {
            throw new RuntimeException("全局经验表数据为空");
        }
        return values;
    }   
    
    public CoreExperience getCache(Integer level,Integer type) {
        Map<String, CoreExperience> values = cache.getIfPresent("coreExperience");
        if (Objects.isNull(values)) {
            throw new RuntimeException("全局经验表数据为空");
        }
        return values.get(level + "-" + type);
    }
}
